package com.choosefine.springboot.devops.activity.controller;


import com.choosefine.springboot.devops.activity.dto.InsertActivityDTO;
import com.choosefine.springboot.devops.activity.dto.UpdateActivityDTO;
import com.choosefine.springboot.devops.activity.model.Activity;
import com.choosefine.springboot.devops.activity.service.ActivityService;
import com.choosefine.springboot.devops.activity.vo.ActivityAndImgVO;
import com.choosefine.springboot.devops.activityImg.model.ActivityImg;
import com.choosefine.springboot.devops.activityImg.service.ActivityImgService;
import com.choosefine.springboot.devops.base.config.FileUtil;
import com.choosefine.springboot.devops.base.config.MapUtil;
import com.choosefine.springboot.devops.base.config.UrlUtil;
import com.choosefine.springboot.devops.base.result.ReturnMSG;
import com.choosefine.springboot.devops.base.serviceImpl.RedisServiceImpl;
import com.choosefine.springboot.devops.rules.service.RulesService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.*;

@RestController
@RequestMapping("/activity")
public class ActivityController {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RedisServiceImpl redisService;
    @Autowired
    private ActivityImgService activityImgService;
    @Autowired
    private RulesService rulesService;



    private static final Logger logger = LoggerFactory.getLogger(ActivityController.class);

    @GetMapping("/{id}")
    public String selectById(@PathVariable("id") Integer id, HttpServletResponse response) throws IOException {
        ReturnMSG returnMSG=new ReturnMSG();
        Activity result = activityService.selectById(id);
        List<ActivityImg> activityImgs =activityImgService.selectByActivityId(id);
        ActivityAndImgVO activityAndImgVO=new ActivityAndImgVO();
        activityAndImgVO.setActivity(result);
        activityAndImgVO.setActivityImgList(activityImgs);
        activityAndImgVO.setHttp(UrlUtil.getHttpHead()+"/activity/img?url=");
        return objectMapper.writeValueAsString(returnMSG.success(activityAndImgVO));
    }

    @PostMapping()
    public String save(@Valid InsertActivityDTO insertActivityDTO,  BindingResult result) throws JsonProcessingException {
        ReturnMSG returnMSG = new ReturnMSG();
        if (result.hasErrors()) {
            return objectMapper.writeValueAsString(returnMSG.paramError());
        } else {
            List<String> urlList=new ArrayList<String>();
            MultipartFile main=insertActivityDTO.getMain();
            if(!FileUtil.uploadsUtil(UrlUtil.getFilePath(),main,urlList)){
                //代表上传错误。可以考虑是否删掉以上传成功的图片。
                FileUtil.deleteUtil(UrlUtil.getFilePath(),urlList);
                return objectMapper.writeValueAsString(returnMSG.uploadError());
            }
            List ewm=new ArrayList();
            if(!FileUtil.uploadsUtil(UrlUtil.getFilePath(),insertActivityDTO.getShopewm(),urlList)){
                //代表上传错误。可以考虑是否删掉以上传成功的图片。
                FileUtil.deleteUtil(UrlUtil.getFilePath(),urlList);
                return objectMapper.writeValueAsString(returnMSG.uploadError());
            }
            Activity param = new Activity();
            BeanUtils.copyProperties(insertActivityDTO, param);
            param.setImg(urlList.get(0));
            param.setShopewm(urlList.get(1));
            param.setCreateTime(new Date());
            param.setStatus((byte) 1);
            int i=activityService.save(Activity.class, MapUtil.transBean2Map(param));
            if(i!=0){
                saveImg(insertActivityDTO.getAppended(),i);
                redisService.set("Activity"+i,objectMapper.writeValueAsString(param));
            }else{
                return objectMapper.writeValueAsString(returnMSG.error());
            }
            return objectMapper.writeValueAsString(returnMSG.success());
        }
    }

    private void saveImg(MultipartFile[] appended,Integer activity){
        ActivityImg img=new ActivityImg();
        img.setActivityId(activity);
        img.setCreateTime(new Date());
        img.setStatus((byte) 1);
        List<String> urlList=new ArrayList<String>();
        if(!FileUtil.uploadsUtil(UrlUtil.getFilePath(),appended,urlList)){
            //代表上传错误。可以考虑是否删掉以上传成功的图片。
            FileUtil.deleteUtil(UrlUtil.getFilePath(),urlList);
        }
        activityImgService.saveArray(img,urlList);
    }

    @GetMapping("/")
    public String selectList() throws JsonProcessingException {
        List<Activity> list = activityService.selectList(1, 10);
        return objectMapper.writeValueAsString(list);
    }

    @PutMapping()
    public String update(UpdateActivityDTO updateActivityDTO) throws JsonProcessingException {
        ReturnMSG returnMSG = new ReturnMSG();
        if (updateActivityDTO.getId() == null) {
            return objectMapper.writeValueAsString(returnMSG.error());
        }
        if (activityService.update(Activity.class, MapUtil.transBean2Map(updateActivityDTO)) > 0) {
            return objectMapper.writeValueAsString(returnMSG.success());
        } else {
            return objectMapper.writeValueAsString(returnMSG.error());
        }
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id) throws JsonProcessingException {
        ReturnMSG returnMSG = new ReturnMSG();
        if (id == null) {
            return objectMapper.writeValueAsString(returnMSG.paramError());
        } else {
            Map param = new HashMap();
            param.put("id", id);
            param.put("status", 2);
            if (activityService.falseDelete(Activity.class, param) > 0) {
                return objectMapper.writeValueAsString(returnMSG.success());
            } else {
                return objectMapper.writeValueAsString(returnMSG.error());
            }
        }
    }

    @GetMapping("/img")
    public void readImg(String url, HttpServletResponse response, HttpServletRequest request) throws IOException {
        FileInputStream fis = null;
        response.setContentType("image/gif");
        try {
            OutputStream out = response.getOutputStream();
            File file = new File(UrlUtil.getFilePath() + url);
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

